﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CPETwit.Web.CustomClass;
using CPETwit.Web.Service.Implementation;
using CPETwit.Web.Service.Interface;
using CPETwit.Data.Entity;
using Twitterizer.Entities;
using Twitterizer.Core;
using Twitterizer;
using CPETwit.Web.Converter;
using System.Text.RegularExpressions;


namespace CPETwit.Web.Pages
{
    public partial class timeline : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Redirige l'internaute si celui-ci n'est pas connecté via session
            isLoggedViaSession();

            //Recherche par tweets
            if (!String.IsNullOrEmpty(Request.Form["q"]))
            {
                ListTweetUtilisateurCourant.Visible = false;
                ListView3.Visible = true;
                ListView4.Visible = false;

            }//Recherche par tag
            else if(!String.IsNullOrEmpty(Request.QueryString["q"]))
            {
                
                ListTweetUtilisateurCourant.Visible = false;
                ListView3.Visible = false;
                ListView4.Visible = true;
                q.Text = String.Empty;
            }//Timeline
            else
            {
                ListTweetUtilisateurCourant.Visible = true;
                ListView3.Visible = false;
                ListView4.Visible = false;
                q.Text = String.Empty;
            }
           
            ITwitterService twitterService = new TwitterService();
            IEnumerable<Tweet> tweets = twitterService.GetAllTweetsByUserId(((User)Session["login"]).id);
            this.nb_tweet.Text = tweets.Count().ToString();
            IEnumerable<User> users = twitterService.GetFollowers((User)Session["login"]);
            this.nb_abonne.Text = users.Count().ToString();
            IEnumerable<User> publishers = twitterService.GetPublishers((User)Session["login"]);
            this.nb_abonnement.Text = publishers.Count().ToString();
        }
        

        protected String getTweetDate( ){
            Tweet t = new Tweet();
            ListView x= this.ListTweetUtilisateurCourant;
            if (t == null)
            {
                return "";
            }
            TimeConverter tc = new TimeConverter();
            return tc.Convert(new DateTime()).ToString();
        }

        public static string  parseTweet(String contenu)
        {
            if (String.IsNullOrEmpty(contenu))
            {
                return "";
            }

            string[] words = contenu.Split(' ');
            List<string> arob = new List<string>();
            List<string> tags = new List<string>();
            string code_arrobase = "";
            string code_tag = "";
            String value = "";
            foreach (var item in words)
            {
                if (item.StartsWith("@"))
                    arob.Add(item);
            }
            foreach (var item in words)
            {
                if (item.StartsWith("#"))
                    tags.Add(item);
            }
            foreach (var item in arob)
            {
                string value_arrobase = item.ToString();
                value = item.ToString();
                value = value.Substring(1, value.Length - 1);
                code_arrobase = "<a href=\"profil.aspx?login=" + value + "\">@" + value + "</a>";
                contenu = contenu.Replace(value_arrobase, code_arrobase);

            }
            foreach (var item in tags)
            {
                string value_tags = item.ToString();
                value = item.ToString();
                value = value.Substring(1, value.Length - 1);
                code_tag = "<a href=\"timeline.aspx?q="+value+"\">#" + value+"</a>";
                contenu = contenu.Replace(value_tags, code_tag);

            }

            
            string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-zA-Z0-9-]+\.[a-zA-Z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
            string short_url = "";
            MatchCollection urls = Regex.Matches(contenu, regex);


            value = "";
            //string url;
            foreach (var item in urls)
            {
                value = item.ToString();

                short_url = "<a href=\"" + value + "\">" + value + "</a>";
                contenu = contenu.Replace(value, short_url);

            }



            return contenu;
        }

        
        public static string SecondsRemaining(DateTime? dt)
        {
            TimeConverter timeConverter = new TimeConverter();
            return timeConverter.Convert(dt.Value) as string;
        }

        protected void list_onItemCreated(object sender, ListViewItemEventArgs e)
        {
            ListViewItem currentItem = e.Item;
            Tweet currentPublisher = (Tweet)currentItem.DataItem;
            //parseTweet(currentPublisher);
        }


        protected void test(object sender, EventArgs e)
        {
            LinkButton b = sender as LinkButton;
            
            //throw new Exception("Pas encore implémenté - utiliser les surcharges d'EvenArgs");
            ITwitterService twitterService = new TwitterService();
            Tweet retweet = new Tweet();
            retweet = twitterService.getTweetFromId(Int64.Parse(b.CommandArgument)).FirstOrDefault();
            //retweet.twitter = ((User)Session["login"]).id;
            //retweet.message = Int64.Parse(b.CommandArgument);
            //retweet.tweetdate = new DateTime();
            //User u = new User();
            //u.id = ((User)Session["login"]).id;
            twitterService.ReTweet((User)Session["login"], retweet, CheckBox_twitterizer.Checked);
        }

        /// <summary>
        /// Action de tweeter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TweetButton_Click(object sender, EventArgs e)
        {
            ITwitterService twitterService = new TwitterService();
            twitterService.SaveTweet((User)Session["login"], this.TweetPost.Text, CheckBox_twitterizer.Checked);
            this.TweetPost.Text = "";
            Response.Redirect("timeline.aspx");
            
        }

        protected void searchTweet(object sender, EventArgs e)
        {
            LinkButton b = sender as LinkButton;
        }

        /// <summary>
        /// Action de se déconnecter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DisconnectButton_Click(object sender, EventArgs e)
        {
            Session.Remove("login");
            Response.Redirect("connexion.aspx");
        }

        /// <summary>
        /// Test si l'internaute est connecté ;
        /// Si ce n'est pas le cas, on le redirige vers la page d'accueil
        /// </summary>
        private void isLoggedViaSession(){
            bool isConnected = false;
            foreach (var item in Session.Keys)
            {
                if (String.Equals(item, "login"))
                {
                    isConnected = true;
                    break;
                }
            }
            if (!isConnected)
            {
                Response.Redirect("connexion.aspx");
            }
        }
    }
}